package com.nexus.plugin.security.service;

import com.nexus.core.exception.AuthenicException;
import com.nexus.core.auth.LoginUser;
import com.nexus.plugin.security.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

/**
 * Security登录实现
 *
 * @Date 2025/8/1 15:47
 * @Author luzhengning
 **/
@Service
public class SecurityLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 系统用户登录
     *
     * @Date 2025/8/1 15:49
     * @Author luzhengning
     **/
    public LoginUser sysLogin(LoginUser loginParam) throws AuthenicException {
        // 调用Security登录验证流程
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginParam.getUsername(), loginParam.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 获取用户信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        // 注册登录用户到系统中
        loginUser = SecurityUtils.RegisterLoginUser(loginUser);
        return loginUser;
    }
}
